package com.ph.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ph.mapper.UserMapper;
import com.ph.config.PhonePasswordToken;
import com.ph.pojo.Department;
import com.ph.pojo.User;
import com.ph.service.DepartmentService;
import com.ph.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public String login(PhonePasswordToken phonePasswordToken) {
        Subject subject = SecurityUtils.getSubject();
        subject.login(phonePasswordToken);
        String uuid ="NEKOT" + UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(uuid, subject.getPrincipal());
        return uuid;

    }

    @Override
    public List<User> findAll(Integer departmentId, String status) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<Department> departments = departmentService.findByParentId(departmentId);
        List<Integer> ids = getIds(departmentId, departments);
        return baseMapper.findAll(ids, status);
    }

    public List<Integer> getIds(Integer departmentId, List<Department> departments){
        List<Integer> ids = new ArrayList<>();
        ids.add(departmentId);
        for (Department department : departments){
            ids.add(department.getId());
            if (department.getDepartments() == null){
                ids.addAll(getIds(department.getId(), department.getDepartments()));
            }
        }
        return ids;
    }
}
